package com.elysia.visionmanagerspringboot.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.elysia.visionmanagerspringboot.context.BaseContext;
import com.elysia.visionmanagerspringboot.domain.dto.ResetPasswordDTO;
import com.elysia.visionmanagerspringboot.domain.dto.UserDTO;
import com.elysia.visionmanagerspringboot.domain.entity.User;
import com.elysia.visionmanagerspringboot.mapper.UserMapper;
import com.elysia.visionmanagerspringboot.properties.JwtProperties;
import com.elysia.visionmanagerspringboot.result.Result;
import com.elysia.visionmanagerspringboot.service.IUserService;
import com.elysia.visionmanagerspringboot.untils.JwtUtils;
import com.elysia.visionmanagerspringboot.untils.PasswordEncoderUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@RequiredArgsConstructor
@Service
@Slf4j
public class IUserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    private final JwtProperties jwtProperties;
    @Override
    public Result<Object> login(UserDTO userDTO, HttpServletResponse response) {
        User user = lambdaQuery().eq(User::getPhone, userDTO.getPhone()).one();
        if (user == null) return Result.error("用户不存在");
        // 即判断该用户是否是初始密码，初始密码的话则用equals判断而不是加密判断
        if (user.getPassword().equals("123456")){
            if (!user.getPassword().equals(userDTO.getPassword()))
                return Result.error("密码错误");
        }
        // 否则用加密判断
        else if (!PasswordEncoderUtil.matches(userDTO.getPassword(), user.getPassword()))
            return Result.error("密码错误");
        // 密码正确，生成JWT并返回给前端
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        String jwt = JwtUtils.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), claims);
        // 创建Cookie对象（使用标准Cookie类）
        Cookie jwtCookie = new Cookie(jwtProperties.getAdminTokenName(), jwt);
        // 设置Cookie属性
        jwtCookie.setHttpOnly(true);  // 禁止JS访问
        jwtCookie.setPath("/");       // 全站有效
        jwtCookie.setMaxAge(86400);    // 有效期（秒）
        // 添加到响应
        response.addCookie(jwtCookie);
        return Result.success();
    }

    @Override
    public Result<Object> reset(ResetPasswordDTO resetPasswordDTO) {
        String encodedPassword = PasswordEncoderUtil.encode(resetPasswordDTO.getPassword());
        lambdaUpdate().eq(User::getId, BaseContext.getCurrentId()).set(User::getPassword, encodedPassword).update();
        return Result.success();
    }
}
